
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

//从根到叶的二进制数之和
class Solution {
public:
    int dfs(TreeNode* root, int num)
    {
        if (root == nullptr)
        {
            return 0;
        }
        
        num = (num << 1) | root->val;

        if (root->left==nullptr && root->right==nullptr)
        {
            return num;
        }

        return dfs(root->left, num) + dfs(root->right, num);
    }

    int sumRootToLeaf(TreeNode* root) {
        return dfs(root, 0);
    }
};